package com.qixin.web.serviceimpl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.qixin.api.bean.*;
import com.qixin.api.mapper.ComPeopleMapper;
import com.qixin.api.service.*;
import com.qixin.util.cache.EhcacheUtil;
import com.qixin.util.sms.SmsMark;
import com.qixin.util.sms.SmsUtil;
import com.qixin.util.weixin.WxpubOAuth;
import com.qixin.util.weixin.bean.OAuthResult;
import com.qixin.web.bean.WeUser;
import com.qixin.web.mapper.WeUserMapper;
import com.qixin.web.service.WeUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 微信充电桩用户 服务实现类
 * </p>
 *
 * @author 张子艺
 * @since 2018-10-02
 */
@Service
public class WeUserServiceImpl extends ServiceImpl<WeUserMapper, WeUser> implements WeUserService {

    private static final Logger logger = LoggerFactory.getLogger(WeUserServiceImpl.class);

     @Autowired
    ComIdcardFileService comIdcardFileService;
     @Autowired
    ComLicenseFileService comLicenseFileService;
     @Autowired
    ComPlaycarFileService comPlaycarFileService;
    @Autowired
    ComPtUserService comPtUserService;
    @Autowired
    ComPeopleService comPeopleServicel;
    @Autowired
    ComPeopleMapper comPeopleMapper;

    @Override    // TODO: 2018/10/29 为什么， 不用工厂模式呢  ？  因为我懒！！！
    public FileResult fileUpload(MultipartFile multipartFile, String flag) {
        switch (flag){
           // a1 营业执照
            case "a1":
                ComLicenseFile comLicenseFile=new ComLicenseFile();
                comLicenseFile.setFlag(1);
               return comLicenseFileService.upload(multipartFile,comLicenseFile);

            //b1身份证正面
            case "b1":
                ComIdcardFile comIdcardFile=new ComIdcardFile();
                comIdcardFile.setFlag(1);
                return  comIdcardFileService.upload(multipartFile,comIdcardFile);
            // b2 身份证反面
            case "b2":
                ComIdcardFile comIdcardFile2=new ComIdcardFile();
                comIdcardFile2.setFlag(2);
                return  comIdcardFileService.upload(multipartFile,comIdcardFile2);
            //c1 驾驶证正面
            case "c1":
                ComPlaycarFile comPlaycarFile=new ComPlaycarFile();
                comPlaycarFile.setFlag(1);
               return comPlaycarFileService.upload(multipartFile,comPlaycarFile);
            //c2驾驶证反面
            case "c2":
                ComPlaycarFile comPlaycarFile2=new ComPlaycarFile();
                comPlaycarFile2.setFlag(2);
                return comPlaycarFileService.upload(multipartFile,comPlaycarFile2);
        default:
           return  new FileResult();
        }
    }

    @Override
    public String SendSMS(Long phone) {
        SendSmsResponse response;
        String code= SmsMark.getCode();

        try {
            response =  SmsUtil.sendSms(phone+"", SmsMark.SMS_MARK,code);
        } catch (ClientException e) {
            e.printStackTrace();
            return  "服务器出错，请稍后再试";
        }
        //验证码获取成功后
        if(response.getMessage().equals("OK")){
            //存进cache缓存  180后过期  当访问过一次后 60秒内没有再此访问 同样过期 缓存区的key设置成数字加字符串 否则获取不到
            EhcacheUtil.put("SMS",phone+"Data",code);
                        System.out.println(code);
            return  "获取验证码成功";
        }
        return "获取短信验证码失败";
    }

    @Override
    public String insertPt(String param, String code, String url) {
        ComPtUser comPtUser=  JSONObject.parseObject(param,ComPtUser.class);
//        Map map1=new HashMap<>();
//        map1.put("call_phone",comPtUser.getCallPhone());
//      List<ComPtUser> comPtUsers= comPtUserService.selectByMap(map1);
//        if(comPtUsers.size()>0){
//            return "该手机号已被注册";
//
//        }
        comPtUser.setFlag(2+"");
        comPtUser.setFalseInfo("新注册用户，暂未审核");
        comPtUser.setUserName(comPtUser.getCallPhone());
        comPtUser.setCreateTime(new Date().getTime());
        if(!equalsCache(code,comPtUser.getCallPhone())){
            return  "验证码错误";
        }
        comPtUserService.insert(comPtUser);
        //关联图片ID
        Map map=new HashMap<>();
        map.put("url",url);
       List<ComLicenseFile> comLicenseFiles   = comLicenseFileService.selectByMap(map) ;
        ComLicenseFile comLicenseFile=comLicenseFiles.get(0);
        comLicenseFile.setRelactionId(comPtUser.getId());
        if(comLicenseFileService.updateById(comLicenseFile)){
            return "注册成功";
        };
        return "false";
    }

    @Override

    public String insertPeople(String param, String code, String b1url, String b2url, String c1url, String c2url)  {
        ComPeople comPeople=JSONObject.parseObject(param,ComPeople.class);
        System.out.println("b1url"+b1url);

//        Map map1=new HashMap<>();
//        map1.put("phone",comPeople.getPhone());
//        List<ComPeople> comPeoples=comPeopleServicel.selectByMap(map1);
//        if(comPeoples.size()>0){
//            return "该手机号已被注册";
//        }
        comPeople.setCreateTime(new Date().getTime());
        comPeople.setFlag(2+"");
        comPeople.setSumMoeny(0);
        comPeople.setUserName(comPeople.getPhone()+"");
        if(!equalsCache(code,comPeople.getPhone()+"")){
            return  "验证码错误";
        }
       if(comPeopleServicel.insert(comPeople)){

        Map map = new HashMap<>();

if(b1url!=""){
    map.put("url", b1url);
    //身份证 正面 关联图片ID
    List<ComIdcardFile> comIdcardFiles = comIdcardFileService.selectByMap(map);
    ComIdcardFile comIdcardFile = comIdcardFiles.get(0);
    comIdcardFile.setRelactionId(comPeople.getId());
  comIdcardFileService.updateById(comIdcardFile);
    map.clear();
}

if (b2url!=""){
    map.put("url", b2url);
    List<ComIdcardFile> comIdcardFiles2 = comIdcardFileService.selectByMap(map);
    ComIdcardFile comIdcardFile2 = comIdcardFiles2.get(0);
    comIdcardFile2.setRelactionId(comPeople.getId());
    comIdcardFileService.updateById(comIdcardFile2);
    map.clear();
}

if(c1url!=""){
    map.put("url", c1url);
    List<ComPlaycarFile> comPlaycarFiles = comPlaycarFileService.selectByMap(map);
    ComPlaycarFile comPlaycarFile = comPlaycarFiles.get(0);
    comPlaycarFile.setRelactionId(comPeople.getId());
    comPlaycarFileService.updateById(comPlaycarFile);
    map.clear();
}

if(c2url!="") {
    map.put("url", c2url);
    List<ComPlaycarFile> comPlaycarFiles2 = comPlaycarFileService.selectByMap(map);
    ComPlaycarFile comPlaycarFile2 = comPlaycarFiles2.get(0);
    comPlaycarFile2.setRelactionId(comPeople.getId());
  comPlaycarFileService.updateById(comPlaycarFile2);
}
if(b1url==""&&b2url==""&&c1url==""&&c2url==""){
    Map map3=new HashMap<>();
    map3.put("phone",comPeople.getPhone());
    List<ComPeople> comPeoplea=comPeopleMapper.selectByMap(map3);
    Long id=comPeoplea.get(0).getId();
    System.out.println(id);
    ComPlaycarFile comPlaycarFileq=new ComPlaycarFile();
    comPlaycarFileq.setRelactionId(id);
    comPlaycarFileq.setCreateTime(new Date().getTime());
    comPlaycarFileq.setFlag(1);
   comPlaycarFileService.insert(comPlaycarFileq);
   ComIdcardFile comIdcardFileq=new ComIdcardFile();
    comIdcardFileq.setRelactionId(id);
    comIdcardFileq.setCreateTime(new Date().getTime());
    comIdcardFileq.setFlag(1);
comIdcardFileService.insert(comIdcardFileq);


}}
        return "注册成功";
    }

    @Override
    public boolean equalsCache(String code,String phone) {

        //从缓存中获取六位验证码 当访问过一次后 60秒内没有再此访问会过期  缓存区的key设置成数字加字符串 否则获取不到
        String cacheCode=EhcacheUtil.get("SMS",phone+"Data")+"";
        logger.info("缓存中的验证码："+cacheCode);
        logger.info("用户输入的验证码："+code);
        logger.info("用户手机号："+phone);
        if (code.equals(cacheCode)){
            return true;
        }
        return false;
    }

    @Override
    public String login(String userName, String passWord,String flag, HttpSession session) {
        //企业登陆
        if(flag.equals("1")){
          Map map=new HashMap<>();
            map.put("user_name",userName);
            map.put("pass_word",passWord);
         List<ComPtUser> comPtUsers=   comPtUserService.selectByMap(map);
            if(comPtUsers.size()==0){
                return "账户密码错误";
            }
            ComPtUser comPtUser= comPtUsers.get(0);
            if(comPtUser.getFlag().equals("2")){
                return "该用户还未通过审核，暂无法登陆";
            }

            session.setAttribute("pt_user",comPtUser);
            String perurl=(String)session.getAttribute("preUrl");
            if (session.getAttribute("preUrl")!=null){
                session.removeAttribute("preUrl");
                return perurl;
            }
           return "true";
        }
        //个人登陆
        if(flag.equals("2")){
            Map map=new HashMap<>();
            map.put("user_name",userName);
            map.put("pass_word",passWord);
            List<ComPeople> comPeoples=   comPeopleServicel.selectByMap(map);
            if(comPeoples.size()==0){
                return "账户密码错误";
            }
            ComPeople comPeople= comPeoples.get(0);
            if(comPeople.getFlag().equals("2")){
                return "该用户还未通过审核，暂无法登陆";
            }
            session.setAttribute("people_user",comPeople);
            String perurl=(String)session.getAttribute("preUrl");
            if (session.getAttribute("preUrl")!=null){
                session.removeAttribute("preUrl");
                return perurl;
            }

            return "true";
        }
        return "服务器出错，请稍后再试";
    }

    @Override
    public boolean weixinLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws UnsupportedEncodingException {
        WxpubOAuth wxpubOAuth = new WxpubOAuth();
        //获取回调后 微信发送的code
        String code = request.getParameter("code");
        //根据code 等信息 取得openid 和 accesstoken
        OAuthResult oAuthResult = WxpubOAuth.getOpenId(WxpubOAuth.APPID,WxpubOAuth.appSecret, code);
        String openId = oAuthResult.getOpenid();
        String access_token = oAuthResult.getAccess_token();
        //根据 openid 和access_token  取得当前授权登陆的用户信息
        String userInfo = WxpubOAuth.getUserContent(access_token, openId, "zh_CN");
        logger.info("当前授权登陆用户：" + userInfo);
        WeUser weUser = JSONObject.parseObject(userInfo, WeUser.class);
        session.setAttribute("we_user", weUser);
        Map map=new HashMap<>();
        map.put("openid",weUser.getOpenid());
        //如果数据库中 不存在该用户  也就是 该用户新关注的 并没有登陆过公众号 那就在数据库保存该用户信息
        if(!(this.selectByMap(map).size()>0)){
            weUser.setWechatFlag(1);
           if(this.insert(weUser)  ) {
               return  true;
           }
        }else {
            return  true;
        }
        return  false;
    }

    @Override
    public Boolean phonetxt(Long phone) {
        Map map1 = new HashMap<>();
        map1.put("phone", phone);
        List<ComPeople> comPeoples = comPeopleServicel.selectByMap(map1);
        if (comPeoples.size() > 0) {
            return false;
        }
        return true;
    }

    @Override
    public Boolean phonetxta(Long phone) {
        Map map2 = new HashMap<>();
        map2.put("call_phone",phone);
        List<ComPtUser> comPtUsers= comPtUserService.selectByMap(map2);
        if (comPtUsers.size() > 0) {
            return false;
        }
        return true;
    }
}
